<template>
  <div class="app-container">
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="150px"
      :label-position="isPhone ? 'top' : 'left'"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="学生" prop="userId" label-width="50px">
            <el-select
              v-model="form.userId"
              placeholder="请选择学生"
              clearable
              :disabled="isDetailMode || isApproveMode"
            >
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <template v-if="formUserInfo">
          <el-col :span="12">
            <el-form-item label="学校" label-width="50px">
              <el-input
                :value="getUniversityText(formUserInfo.trainUniversity)"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" label-width="50px">
              <el-input v-model="formUserInfo.trainMajor" disabled> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培养单位" label-width="80px">
              <el-input v-model="formUserInfo.trainDeptName" disabled>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课题名称" label-width="80px">
              <el-input v-model="formUserInfo.joinEntTopicName" disabled>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课题简介" label-width="80px">
              <el-input
                v-model="formUserInfo.joinEntTopicIntroduction"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="12">
          <el-form-item label="论文开题计划时间" prop="thesisStartTime">
            <el-date-picker
              v-model="form.thesisStartTime"
              type="date"
              placeholder="请选择论文开题计划时间"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              :disabled="isDetailMode"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="中期考核计划时间" prop="thesisMidTime">
            <el-date-picker
              v-model="form.thesisMidTime"
              type="date"
              placeholder="请选择中期考核计划时间"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              :disabled="isDetailMode"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="论文预答辩计划时间" prop="thesisPreTime">
            <el-date-picker
              v-model="form.thesisPreTime"
              type="date"
              placeholder="请选择论文预答辩计划时间"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              :disabled="isDetailMode"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="论文答辩计划时间" prop="thesisEndTime">
            <el-date-picker
              v-model="form.thesisEndTime"
              type="date"
              placeholder="请选择论文答辩计划时间"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              :disabled="isDetailMode"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="计划" label-width="50px">
            <div class="plan-table-container">
              <el-table :data="form.planDetails" border style="width: 100%">
                <el-table-column label="计划名称" width="150" prop="planName" />
                <el-table-column label="计划月份" width="150">
                  <template #default="scope">
                    {{
                      scope.row.planMonth
                        ? formatMonth(scope.row.planMonth)
                        : "-"
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="开始时间"
                  width="150"
                  prop="planStartTime"
                />
                <el-table-column
                  label="结束时间"
                  width="150"
                  prop="planEndTime"
                />
                <el-table-column label="实践目标" min-width="200">
                  <template #default="scope">
                    <div class="text-overflow" :title="scope.row.planTarget">
                      {{ scope.row.planTarget || "-" }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="140" fixed="right">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleEditPlan(scope.row, scope.$index)"
                      v-if="!isDetailMode && !isApproveMode"
                    >
                      编辑
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      @click="removePlan(scope.$index)"
                      v-if="
                        form.approvalStatus !== 'approved' &&
                        !isDetailMode &&
                        !isApproveMode
                      "
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 10px">
                <el-button
                  v-if="
                    (!form.planDetails || form.planDetails?.length < 50) &&
                    !isDetailMode &&
                    !isApproveMode
                  "
                  type="primary"
                  @click="handleAddPlan"
                  size="small"
                >
                  添加计划
                </el-button>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <!-- 审批进度组件 -->
    <div v-if="form.approvalInfoId" style="margin-bottom: 20px">
      <approval-progress :approval-info-id="form.approvalInfoId" />
    </div>
    
    <el-form-item
      label="审核意见"
      prop="approvalRemark"
      style="margin-bottom: 0"
      v-if="form.approvalStatus === 'rejected'"
    >
      <el-input
        v-model="form.approvalRemark"
        disabled
        type="textarea"
        placeholder="请输入审核意见"
        :rows="3"
        style="width: 100%"
      ></el-input>
    </el-form-item>
    <div v-if="isApproveMode" style="margin-bottom: 20px">
      <el-form-item
        label="审核意见"
        prop="approvalRemark"
        style="margin-bottom: 0"
      >
        <el-input
          v-model="form.approvalRemark"
          type="textarea"
          placeholder="请输入审核意见"
          :rows="3"
          style="width: 100%"
        ></el-input>
      </el-form-item>
    </div>
    <div class="dialog-footer" style="margin-top: 20px">
      <template v-if="!isApproveMode && !isDetailMode">
        <el-button
          type="primary"
          @click="submitForm"
          :loading="submitLoading"
          :disabled="submitLoading"
          >确 定</el-button
        >
        <el-button @click="handleBack">取 消</el-button>
      </template>
      <template v-else-if="isDetailMode">
        <el-button @click="handleBack">关 闭</el-button>
      </template>
      <template v-else>
        <el-button
          type="success"
          @click="handleApprovePass"
          :loading="approvePassLoading"
          :disabled="approvePassLoading"
          >通 过</el-button
        >
        <el-button
          type="danger"
          @click="handleApproveReject"
          :loading="approveRejectLoading"
          :disabled="approveRejectLoading"
          >驳 回</el-button
        >
        <el-button @click="handleBack">取 消</el-button>
      </template>
    </div>

    <!-- 计划编辑对话框 -->
    <el-dialog
      :title="planDialogTitle"
      v-model="planDialogVisible"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="planForm"
        :rules="planRules"
        ref="planFormRef"
        label-width="100px"
        :label-position="isPhone ? 'top' : 'left'"
      >
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="planForm.planName" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="计划月份" prop="planMonth">
          <el-date-picker
            v-model="planForm.planMonth"
            type="month"
            placeholder="请选择计划月份"
            style="width: 100%"
            @change="onPlanMonthChange"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="planStartTime">
          <el-date-picker
            v-model="planForm.planStartTime"
            type="date"
            placeholder="请选择开始时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            @change="onStartTimeChange"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="planEndTime">
          <el-date-picker
            v-model="planForm.planEndTime"
            type="date"
            placeholder="请选择结束时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            @change="validatePlanDateRange"
          />
        </el-form-item>
        <el-form-item label="实践目标" prop="planTarget">
          <el-input
            v-model="planForm.planTarget"
            type="textarea"
            :rows="4"
            placeholder="请输入实践目标"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitPlanForm"
            :loading="planSubmitLoading"
            :disabled="planSubmitLoading"
            >确 定</el-button
          >
          <el-button @click="cancelPlanForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EnterprisePracticeEdit">
import moment from "moment";
import {
  addItem,
  editItem,
  getDetail,
} from "@/api/enterprise-practice-program";
import { handleApproval } from "@/api/approval";
import { getStudentList } from "@/api/common";
import useUserStore from "@/store/modules/user";
import { isPhone } from "@/utils/index";
import { useRouter, useRoute } from "vue-router";
import ApprovalProgress from "@/components/ApprovalProgress";

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const { university } = proxy.useDict("university");

const form = ref({
  userId: useUserStore().id,
  thesisStartTime: "",
  thesisMidTime: "",
  thesisPreTime: "",
  thesisEndTime: "",
  planDetails: [],
  approvalRemark: "",
});

const rules = {
  userId: [{ required: true, message: "请选择学生", trigger: "change" }],
  thesisStartTime: [
    { required: true, message: "请选择论文开题计划时间", trigger: "change" },
  ],
  thesisMidTime: [
    { required: true, message: "请选择中期考核计划时间", trigger: "change" },
  ],
  thesisPreTime: [
    {
      required: true,
      message: "请选择论文预答辩计划时间",
      trigger: "change",
    },
  ],
  thesisEndTime: [
    { required: true, message: "请选择论文答辩计划时间", trigger: "change" },
  ],
};

const userList = ref([]);
const formRef = ref();

// 按钮loading状态
const submitLoading = ref(false);
const approvePassLoading = ref(false);
const approveRejectLoading = ref(false);
const planSubmitLoading = ref(false);

// 计划编辑对话框相关数据
const planDialogVisible = ref(false);
const planDialogTitle = ref("");
const planEditIndex = ref(-1);
const planForm = ref({
  planName: "",
  planMonth: "",
  planStartTime: "",
  planEndTime: "",
  planTarget: "",
});

// 计划表单验证规则
const planRules = {
  planName: [{ required: true, message: "请输入计划名称", trigger: "blur" }],
  planMonth: [{ required: true, message: "请选择计划月份", trigger: "change" }],
  planStartTime: [
    { required: true, message: "请选择开始时间", trigger: "change" },
  ],
  planEndTime: [
    { required: true, message: "请选择结束时间", trigger: "change" },
  ],
  planTarget: [{ required: true, message: "请输入实践目标", trigger: "blur" }],
};

const isDetailMode = computed(() => route.query.mode === "detail");
const isApproveMode = computed(() => route.query.mode === "approve");

const formUserInfo = computed(() =>
  userList.value.find((t) => t.userId === form.value.userId)
);

// 高校名称文本显示函数
const getUniversityText = (universityValue) => {
  if (!universityValue) return "未知";
  const dict = university.value?.find((item) => item.value === universityValue);
  return dict ? dict.label : universityValue;
};

// 添加计划
function handleAddPlan() {
  resetPlanForm();
  planEditIndex.value = -1;
  planDialogTitle.value = "添加计划";
  const lastPlanMonth =
    form.value.planDetails[form.value.planDetails.length - 1];
  if (!lastPlanMonth) {
    planForm.value = {
      planName: `第1个月计划`,
      planMonth: moment().format("YYYY-MM-DD"),
      planStartTime: moment().startOf("month").format("YYYY-MM-DD"),
      planEndTime: moment().endOf("month").format("YYYY-MM-DD"),
      planTarget: "",
    };
  } else {
    const nextMonth = moment(new Date(lastPlanMonth.planMonth))
      .add(1, "month")
      .format("YYYY-MM-DD");
    console.log(lastPlanMonth, nextMonth);

    planForm.value = {
      planName: `第${form.value.planDetails.length + 1}个月计划`,
      planMonth: nextMonth,
      planStartTime: moment(nextMonth).startOf("month").format("YYYY-MM-DD"),
      planEndTime: moment(nextMonth).endOf("month").format("YYYY-MM-DD"),
      planTarget: "",
    };
  }

  planDialogVisible.value = true;
}

// 编辑计划
function handleEditPlan(row, index) {
  resetPlanForm();
  planEditIndex.value = index;
  planDialogTitle.value = "编辑计划";

  planForm.value = {
    planName: row.planName || "",
    planMonth: row.planMonth || "",
    planStartTime: row.planStartTime || "",
    planEndTime: row.planEndTime || "",
    planTarget: row.planTarget || "",
  };

  planDialogVisible.value = true;
}

// 重置计划表单
function resetPlanForm() {
  planForm.value = {
    planName: "",
    planMonth: "",
    planStartTime: "",
    planEndTime: "",
    planTarget: "",
  };
  if (proxy.$refs.planFormRef) {
    proxy.$refs.planFormRef.resetFields();
  }
}

// 取消计划编辑
function cancelPlanForm() {
  planDialogVisible.value = false;
  resetPlanForm();
}

// 提交计划表单
function submitPlanForm() {
  if (planSubmitLoading.value) return;

  proxy.$refs.planFormRef.validate((valid) => {
    if (valid) {
      const dateValidation = validateSinglePlanDateRange(planForm.value);
      if (!dateValidation.valid) {
        proxy.$modal.msgError(dateValidation.message);
        return;
      }

      planSubmitLoading.value = true;

      if (!form.value.planDetails) {
        form.value.planDetails = [];
      }

      if (planEditIndex.value === -1) {
        form.value.planDetails.push({ ...planForm.value });
        proxy.$modal.msgSuccess("添加计划成功");
      } else {
        form.value.planDetails[planEditIndex.value] = { ...planForm.value };
        proxy.$modal.msgSuccess("编辑计划成功");
      }

      planDialogVisible.value = false;
      resetPlanForm();
      planSubmitLoading.value = false;
    }
  });
}

// 验证单个计划的日期范围
function validateSinglePlanDateRange(plan) {
  if (!plan.planStartTime || !plan.planEndTime) {
    return { valid: true, message: "" };
  }

  const startDate = new Date(plan.planStartTime);
  const endDate = new Date(plan.planEndTime);

  if (plan.planMonth) {
    const planMonthDate = new Date(plan.planMonth);
    const year = planMonthDate.getFullYear();
    const month = planMonthDate.getMonth();

    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);

    if (startDate < firstDay || startDate > lastDay) {
      return {
        valid: false,
        message: "开始时间必须在计划月份内",
      };
    }
  }

  if (endDate < startDate) {
    return {
      valid: false,
      message: "结束时间不能早于开始时间",
    };
  }

  const timeDiff = endDate.getTime() - startDate.getTime();
  const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

  if (daysDiff > 30) {
    return {
      valid: false,
      message: `时间跨度不能超过1个月（30天），当前为${daysDiff}天`,
    };
  }

  return { valid: true, message: "" };
}

// 实时验证计划日期范围
function validatePlanDateRange() {
  if (!planForm.value.planStartTime || !planForm.value.planEndTime) {
    return;
  }

  const validation = validateSinglePlanDateRange(planForm.value);
  if (!validation.valid) {
    proxy.$modal.msgWarning(validation.message);
  }
}

// 计划月份改变时的处理
function onPlanMonthChange() {
  if (planForm.value.planStartTime || planForm.value.planEndTime) {
    planForm.value.planStartTime = "";
    planForm.value.planEndTime = "";
    proxy.$modal.msgInfo("计划月份已更改，请重新选择开始时间和结束时间");
  }
}

// 开始时间改变时的处理
function onStartTimeChange(value) {
  validatePlanDateRange();
}

// 格式化月份显示
function formatMonth(monthValue) {
  if (!monthValue) return "";
  const date = new Date(monthValue);
  return `${date.getFullYear()}年${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}月`;
}

function removePlan(index) {
  if (form.value.planDetails && form.value.planDetails.length > 1) {
    form.value.planDetails.splice(index, 1);
  }
}

// 校验计划详情
function validatePlanDetails() {
  if (!form.value.planDetails || form.value.planDetails.length === 0) {
    return {
      valid: false,
      message: "至少需要添加一个计划",
    };
  }

  for (let i = 0; i < form.value.planDetails.length; i++) {
    const plan = form.value.planDetails[i];
    const rowIndex = i + 1;

    if (!plan.planName || !plan.planName.trim()) {
      return {
        valid: false,
        message: `第${rowIndex}行：计划名称不能为空`,
      };
    }

    if (!plan.planMonth) {
      return {
        valid: false,
        message: `第${rowIndex}行：计划月份不能为空`,
      };
    }

    if (!plan.planStartTime) {
      return {
        valid: false,
        message: `第${rowIndex}行：开始时间不能为空`,
      };
    }

    if (!plan.planEndTime) {
      return {
        valid: false,
        message: `第${rowIndex}行：结束时间不能为空`,
      };
    }

    if (!plan.planTarget || !plan.planTarget.trim()) {
      return {
        valid: false,
        message: `第${rowIndex}行：实践目标不能为空`,
      };
    }

    const startDate = new Date(plan.planStartTime);
    const endDate = new Date(plan.planEndTime);

    if (endDate < startDate) {
      return {
        valid: false,
        message: `第${rowIndex}行：结束时间不能早于开始时间`,
      };
    }

    const timeDiff = endDate.getTime() - startDate.getTime();
    const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

    if (daysDiff > 30) {
      return {
        valid: false,
        message: `第${rowIndex}行：时间跨度不能超过1个月（30天），当前为${daysDiff}天`,
      };
    }
  }

  return {
    valid: true,
    message: "",
  };
}

/** 提交按钮 */
function submitForm() {
  if (submitLoading.value) return;

  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      const planValidationResult = validatePlanDetails();
      if (!planValidationResult.valid) {
        proxy.$modal.msgError(planValidationResult.message);
        return;
      }

      submitLoading.value = true;
      const submitData = {
        ...form.value,
      };

      if (form.value.id != undefined) {
        editItem(submitData)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            handleBack();
          })
          .catch((error) => {
            console.error("修改失败:", error);
          })
          .finally(() => {
            submitLoading.value = false;
          });
      } else {
        addItem(submitData)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            handleBack();
          })
          .catch((error) => {
            console.error("新增失败:", error);
          })
          .finally(() => {
            submitLoading.value = false;
          });
      }
    }
  });
}

// 通过审批
function handleApprovePass() {
  if (approvePassLoading.value) return;

  approvePassLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "approved",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData)
    .then(() => {
      proxy.$modal.msgSuccess("审批通过");
      handleBack();
    })
    .catch((error) => {
      console.error("审批通过失败:", error);
    })
    .finally(() => {
      approvePassLoading.value = false;
    });
}

// 驳回审批
function handleApproveReject() {
  if (!form.value.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  if (approveRejectLoading.value) return;

  approveRejectLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData)
    .then(() => {
      proxy.$modal.msgSuccess("已驳回");
      handleBack();
    })
    .catch((error) => {
      console.error("审批驳回失败:", error);
    })
    .finally(() => {
      approveRejectLoading.value = false;
    });
}

function handleBack() {
  router.go(-1);
}

// 初始化
function initPage() {
  const id = route.params.id;
  if (id && id !== "new") {
    getDetail(id).then((response) => {
      form.value = response.data;
      if (!form.value.planDetails) {
        form.value.planDetails = [];
      }
    });
  }
}

onMounted(() => {
  getStudentList({ roleKey: "student" }).then((res) => {
    userList.value = res.data;
  });
  initPage();
});
</script>

<style scoped>
.text-overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 200px;
}

.plan-table-container {
  width: 100%;
}

.plan-table-container .el-table {
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>
